package com.wmada.toolkit.common.secure;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author will.ma
 * @date 2017/3/11
 */
public class Encrypt {

    private static final Logger LOGGER = LoggerFactory.getLogger(Encrypt.class);

    private Cipher cipher = null;

    public Encrypt(String algorithm, String keyAlgorithm, String password) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(password.getBytes(StandardCharsets.UTF_8), keyAlgorithm);
            cipher = Cipher.getInstance(algorithm);//"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
            LOGGER.warn("初始化Encrypt失败", e);
        }
    }

    public Encrypt(String algorithm, String keyAlgorithm, byte[] password) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(password, keyAlgorithm);
            cipher = Cipher.getInstance(algorithm);//"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
            LOGGER.warn("初始化Encrypt失败", e);
        }
    }

    public String encrypt(String message) {
        if (cipher != null && message != null) {
            try {
                return EncodeUtils.base64Encode(cipher.doFinal(message.getBytes(StandardCharsets.UTF_8)));
            } catch (BadPaddingException | IllegalBlockSizeException e) {
                LOGGER.warn("加密字符串失败", e);
                return null;
            }
        } else {
            return null;
        }
    }

    public byte[] encrypt(byte[] data) {
        if (cipher != null && data != null) {
            try {
                return cipher.doFinal(data);
            } catch (BadPaddingException | IllegalBlockSizeException e) {
                LOGGER.warn("加密字符串失败", e);
                return null;
            }
        } else {
            return null;
        }
    }

}
